package com.szt.ynb.server.router.controller;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.szt.ynb.server.router.entity.Server;
import com.szt.ynb.server.router.service.ServerService;
import com.szt.ynb.server.router.vo.base.RepBaseVO;

@RestController
@RequestMapping("server")
public class ServerController {
	
	@Autowired
	private ServerService serverService;
	
	/***
	 * 服务上线
	 * 
	 * @param serverName
	 * @param version
	 * @param url
	 * @return
	 */
	@PostMapping("online")
	public RepBaseVO<Long> online(String serverName, String version, String url) {
		RepBaseVO<Long> repVO = new RepBaseVO<>();
		Server server = serverService.findByServerNameAndVersionAndUrl(serverName, version, url);
		Date now = new Date();
		if (server == null) {
			server = new Server();
			server.setAddDate(now);
			server.setServerName(serverName);
			server.setVersion(version);
			server.setUrl(url);
			server.setUpdateDate(now);
			server.setStatus(Server.STATUS_ONLINE);
		} else {
			server.setUpdateDate(now);
			server.setStatus(Server.STATUS_ONLINE);
		}
		server = serverService.save(server);
		return repVO.setCommonSuccess().setData(server.getId());
	}
	
	/****
	 * 服务下线
	 * 
	 * @param serverName
	 * @param version
	 * @param url
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@PostMapping("offline")
	public RepBaseVO offline(Long id) {
		RepBaseVO repVO = new RepBaseVO<>();
		Server server = serverService.findById(id);
		Date now = new Date();
		if (server == null) {
			
		} else {
			server.setUpdateDate(now);
			server.setStatus(Server.STATUS_OFFLINE);
		}
		serverService.save(server);
		return repVO.setCommonSuccess();
	}
	
	/***
	 * 保持心跳
	 * 
	 * @param id
	 * @return
	 */
	@PostMapping("heartbeat")
	public RepBaseVO heartbeat(Long id) {
		RepBaseVO repVO = new RepBaseVO<>();
		Server server = serverService.findById(id);
		Date now = new Date();
		if (server != null) {
			// 不是强制下线的情况下，修改为上线状态
			if (server.getStatus() != Server.STATUS_FORSE_OFFLINE) {
				server.setUpdateDate(now);
				server.setStatus(Server.STATUS_ONLINE);
			}
			serverService.save(server);
		}
		return repVO.setCommonSuccess();
	}
}
